package com.oitsm.utils;

import java.lang.reflect.Method;

import org.apache.commons.lang.StringUtils;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
/**
 * XML工具
 * @author Arab Runner
 * Aug 7, 2011 11:28:10 AM
 */
public class XMLUtils {
	/**
	 * 获取属性值
	 * @param node
	 * @param name
	 * @return
	 */
	public static String getAttrValue(Node node,String name){
		if(node.getAttributes() == null){
			return null;
		}
		Node attrs = node.getAttributes().getNamedItem(name);
		return attrs==null?null:attrs.getNodeValue();
	}
	
	/**
	 * 将一条XML变成对象 - 只支持普通属性
	 * @param node
	 * @param c
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Object XML2Object(Node node,Class c) throws Exception{
		Object o = null;
		try{
			Method[] ms = c.getMethods();
			o = c.newInstance();
			NamedNodeMap m = node.getAttributes();
			for(int i=0;i<m.getLength();i++){
				Node attr = m.item(i);
				String name = attr.getNodeName();
				if(StringUtils.isNotEmpty(name)){
					String methodName = "set" + name.substring(0,1).toUpperCase() + name.substring(1);
					Method method = null;
					for(Method tmp : ms){
						if(tmp.getName().equals(methodName) && tmp.getParameterTypes().length==1){
							method = tmp;
							break;
						}
					}
					
					if(method!=null){
						String value = attr.getNodeValue();
						Class p = method.getParameterTypes()[0];
						if(p.equals(String.class)){
							method.invoke(o, value);
						}else if(p.equals(int.class) || p.equals(Integer.class)){
							method.invoke(o, Integer.parseInt(value));
						}else if(p.equals(boolean.class) || p.equals(Boolean.class)){
							method.invoke(o, Boolean.parseBoolean(value));
						}
					}
				}
			}
		}catch(Exception e){
			return null;
		}
		return o;
	}
}
